<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools>
        <template v-slot:after>
          <el-button type="primary" size="mini" @click="$router.push('/import')">导入</el-button>
          <el-button type="primary" size="mini" @click="onExcelExport">导出</el-button>
          <el-button icon="el-icon-plus" type="primary" size="mini" @click="showDialog=true">新增员工</el-button>
        </template>
      </PageTools>
      <!--      table-->
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="staffData">
          <el-table-column label="序号" sortable type="index" />
          <el-table-column label="姓名" sortable prop="username" />
          <el-table-column label="头像" center>
            <template v-slot="{row}">
              <el-avatar
                :size="50"
                :src="row.staffPhoto"
                @error="errorHandler"
                @click.native="handleClickAvatar(row.staffPhoto)"
              >
                <img :src="require('@/assets/common/bigUserHeader.png')">
              </el-avatar>
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式" sortable>
            <template v-slot="{row:{formOfEmployment}}">
              {{ formOfEmployment|formatHireType }}
            </template>
          </el-table-column>
          <el-table-column label="部门" sortable>
            <template v-slot="{row:{departmentName}}">
              {{ departmentName || '暂无' }}
            </template>
          </el-table-column>
          <el-table-column label="入职时间" sortable>
            <template v-slot="{row:{timeOfEntry}}">
              {{ timeOfEntry|formatDate('yyyy-mm-dd') }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable>
            <template v-slot="scope">
              {{ scope.row.enableState ? '可用' : '不可用' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{row}">
              <el-button
                :disabled="checkPermission(points.pointUserUpdate)"
                type="text"
                size="small"
                @click="$router.push('/employees/'+row.id)"
              >查看
              </el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="onClickRole(row.id)">角色</el-button>
              <el-button
                :disabled="checkPermission(points.pointUserDelete)"
                type="text"
                size="small"
                @click.native="delEmployees(row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :page-size="tablePage.size"
            layout="total,prev, pager, next"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <AddEmployees v-model="showDialog" />
    <el-dialog :visible.sync="isShowQRCode" center width="25%">
      <canvas id="canvas" />
    </el-dialog>

    <!--    分配角色-->
    <AssignRole :set-role-dialog-visible.sync="SetRoleDialogVisible" :current-employees-id="currentEmployeesId" />
  </div>
</template>

<script>
import { delEmployees, getEmployeesList } from '@/api/employees'
import AddEmployees from '@/views/employees/components/AddEmployees'
import { formatHireType } from '@/filters'
import { formatDate } from '@/utils'
import AssignRole from '@/views/employees/components/AssignRole'
import QRCode from 'qrcode'
import { mapGetters } from 'vuex'

export default {
  name: 'Employees',
  components: {
    AddEmployees,
    AssignRole
  },
  data() {
    return {
      showDialog: false,
      tablePage: {
        page: 1,
        size: 10
      },
      staffData: [],
      total: 0,
      isShowQRCode: false,
      SetRoleDialogVisible: false, // 角色弹窗
      currentEmployeesId: ''
    }
  },
  watch: {
    tablePage: {
      deep: true,
      handler() {
        this.loadTableList()
      }
    }
  },
  computed: {
    ...mapGetters(['roles', 'points'])
  },
  created() {
    this.loadTableList()
  },
  mounted() {

  },
  methods: {
    async loadTableList() {
      const { rows, total } = await getEmployeesList(this.tablePage)
      this.staffData = rows
      this.total = total
    },
    handleCurrentChange(val) {
      this.tablePage.page = val
    },
    // 删除员工
    delEmployees(row) {
      console.log(row)
      this.$confirm('此操作将永久删除员工, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delEmployees(row.id)
        await this.loadTableList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
      })
    },
    // 导出员工
    onExcelExport() {
      import('@/vendor/Export2Excel').then(async excel => {
        const { rows } = await getEmployeesList({
          page: 1,
          size: this.total
        })
        const userRelations = {
          '手机号': 'mobile',
          '姓名': 'username',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        const tHeader = Object.keys(userRelations)
        const data = this.formatExcelData(rows, userRelations, tHeader)
        excel.export_json_to_excel({
          header: tHeader, // 表头 必填
          data, // 具体数据 必填
          filename: '员工列表', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    formatExcelData(rows, userRelations, tHeader) {
      const rep = /^[1-2][0-9][0-9][0-9]\/[0-1]{0,1}[0-9]\/[0-3]{0,1}[0-9]$/
      const rep2 = /^[1-2][0-9][0-9][0-9]-[0-1]{0,1}[0-9]-[0-3]{0,1}[0-9]$/
      return rows.map(item => {
        return tHeader.map(key => {
          const flag = rep.test(item[userRelations[key]]) || rep2.test(item[userRelations[key]]) // 判断格式
          if (rep2.test(item[userRelations[key]])) {
            return item[userRelations[key]].replace(/-/g, '/')
          }
          if ((key === '入职日期' || key === '转正日期') && !flag) {
            return formatDate(item[userRelations[key]], '/')
          } else if (key === '聘用形式') {
            return formatHireType(item[userRelations[key]])
          }
          return item[userRelations[key]]
        }
        )
      })
    },
    // 图片加载失败的回调
    errorHandler(e) {
      console.log(e)
    },
    // 点击图片
    handleClickAvatar(url) {
      if (!url) return this.$message.warning('这是默认图片')
      this.isShowQRCode = true // 数据更新视图没有更新
      this.$nextTick(() => {
        const canvas = document.getElementById('canvas')
        QRCode.toCanvas(canvas, url, function(error) {
          if (error) console.error(error)
          console.log('success!')
        })
      })
    },
    // 点击角色
    onClickRole(roleId) {
      this.SetRoleDialogVisible = true
      this.currentEmployeesId = roleId
    },
    // 检验用户按钮权限
    checkPermission(val) {
      return (this.roles && !this.roles.points.includes(val))
    }

  }
}
</script>

<style scoped lang='scss'>

</style>
